<template>
  <div style="margin: 0;padding: 0">
    <el-container>
      <!--页面表头设计-->
      <el-header style="height: 42px; display: flex; align-items: center; justify-content: space-between; background-color: #409EFF;">
        <span class="center-text" style="color: white; font-size: 18px;">出差管理系统</span>
        <el-popover
            placement="top-start"
            title="用户信息"
            width="200"
            trigger="hover">
          <div style="margin-top: 10px">Name：{{useName}}</div>
          <div style="margin-top: 10px">ID:{{useId}}</div>
          <div style="margin-top: 10px" @click="logOut"><el-link>退出</el-link></div>
          <div class="headMain" slot="reference">{{useName}}</div>
        </el-popover>
      </el-header>

      <el-container>
        <el-aside class="el-aside" width="200px" style="height: auto; min-height: 100vh;">
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 1 ? 'blue' : '',
        color: activeButton === 1 ? 'white' : ''
      }"
              @click="buttonMainSelect(1)">
            出差信息查看
          </el-button>
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 2 ? 'blue' : '',
        color: activeButton === 2 ? 'white' : ''
      }"
              @click="buttonMainSelect(2)">
            出差管理
          </el-button>
          <!-- 添加简化信息查看按钮 -->
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 3 ? 'blue' : '',
        color: activeButton === 3 ? 'white' : ''
      }"
              @click="buttonMainSelect(3)">
            简化信息查看（预算）
          </el-button>
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 4 ? 'blue' : '',
        color: activeButton === 4 ? 'white' : ''
    }"
              @click="buttonMainSelect(4)">
            月度停留统计
          </el-button>
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 5 ? 'blue' : '',
        color: activeButton === 5 ? 'white' : ''
    }"
              @click="buttonMainSelect(5)">
            航班信息
          </el-button>
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 6 ? 'blue' : '',
        color: activeButton === 6 ? 'white' : ''
    }"
              @click="buttonMainSelect(6)">
            电话房间信息
          </el-button>
          <el-button
              class="aside-button"
              :style="{
        backgroundColor: activeButton === 7 ? 'blue' : '',
        color: activeButton === 7 ? 'white' : ''
    }"
              @click="buttonMainSelect(7)">
            月度状态表
          </el-button>

        </el-aside>

        <el-container>
          <!--主题设计-->
          <el-main class="el-main" style="height: calc(100vh - 105px);overflow: auto">
            <!-- 出差信息查看 (只读模式) -->
            <div v-if="buttonDoe === 1">
              <!-- 出差记录表格 (无操作按钮) -->
              <el-table :data="chineseTripData" style="width: 100%" border>
                <el-table-column prop="number" label="工号" width="120"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="department" label="部门" width="120" sortable></el-table-column>
                <el-table-column prop="section" label="科室" width="120" sortable></el-table-column>
                <el-table-column prop="gender" label="性别" width="80"></el-table-column>
                <el-table-column prop="fare" label="费用" width="120"></el-table-column>
                <el-table-column prop="passportNumber" label="护照号码" width="150"></el-table-column>
                <el-table-column prop="business" label="签证" width="150"></el-table-column>
                <el-table-column prop="busineseBegan" label="签证开始时间" width="120"></el-table-column>
                <el-table-column label="签证结束时间" width="120">
                  <template slot-scope="scope">
        <span v-if="scope.row.business === 'business' && scope.row.busineseBegan">
          {{ calculateVisaEndDate(scope.row.busineseBegan) }}
        </span>
                  </template>
                </el-table-column>
                <el-table-column prop="enterRussiaOne" label="第一次入境俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="leftRussiaOne" label="第一次离开俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="enterRussiaTwo" label="第二次入境俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="leftRussiaTwo" label="第二次离开俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="enterRussiaThree" label="第三次入境俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="leftRussiaThree" label="第三次离开俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="enterRussiaFour" label="第四次入境俄罗斯" width="120" sortable></el-table-column>
                <el-table-column prop="leftRussiaFour" label="第四次离开俄罗斯" width="120" sortable></el-table-column>
              </el-table>
            </div>

            <!-- 出差管理 (完整功能) -->
            <!-- 出差管理 (完整功能) -->
            <div v-if="buttonDoe === 2">
              <el-row gutter="20">
                <el-col :span="8">
                  <el-button
                      type="primary"
                      @click="openTripDialog(1, null)"
                      style="margin-bottom: 20px;"
                      v-if="useName === '刘浩'"
                  >
                    添加出差记录
                  </el-button>


                  <el-button
                      type="primary"
                      :style="{
      marginBottom: '20px',
      backgroundColor: cancelSwitch ? '#F56C6C' : '#409EFF',
      borderColor: cancelSwitch ? '#F56C6C' : '#409EFF'
    }"
                      :loading="switchLoading"
                      @click="toggleCancelStatus"
                      v-if="useName === '刘浩'"
                  >
                    {{ cancelSwitch ? '关闭所有记录' : '开启所有记录' }}
                  </el-button>

                  <!-- 添加上传Excel按钮 -->
                  <el-button
                      type="success"
                      @click="openExcelUploadDialog"
                      style="margin-bottom: 20px; margin-left: 10px;"
                      v-if="useName === '刘浩'"
                  >
                    上传Excel文档
                  </el-button>
                  <el-button
                      type="warning"
                      @click="exportAllData"
                      style="margin-bottom: 20px; margin-left: 10px;"
                  >
                    导出全部数据
                  </el-button>
                </el-col>
                <el-col :span="16" style="text-align: right;">
                  <el-button
                      type="text"
                      @click="downloadExcelTemplate"
                      style="margin-bottom: 20px;"
                  >
                    下载Excel模板
                  </el-button>
                </el-col>
              </el-row>

              <el-table :data="filteredChineseTripData" style="width: 100%" border>
                <el-table-column prop="number" label="工号" width="120"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="department" label="部门" width="120" sortable></el-table-column>
                <el-table-column prop="section" label="科室" width="120" sortable ></el-table-column>
                <el-table-column prop="gender" label="性别" width="80"></el-table-column>
                <el-table-column prop="fare" label="费用" width="120"></el-table-column>
                <el-table-column prop="passportNumber" label="护照号码" width="150"></el-table-column>
                <el-table-column prop="business" label="签证" width="150"></el-table-column>
                <el-table-column prop="busineseBegan" label="签证开始时间" width="120"></el-table-column>
                <el-table-column prop="enterRussiaOne" label="第一次入境俄罗斯" width="120" ></el-table-column>
                <el-table-column prop="leftRussiaOne" label="第一次离开俄罗斯" width="120"></el-table-column>
                <el-table-column prop="enterRussiaTwo" label="第二次入境俄罗斯" width="120"></el-table-column>
                <el-table-column prop="leftRussiaTwo" label="第二次离开俄罗斯" width="120"></el-table-column>
                <el-table-column prop="enterRussiaThree" label="第三次入境俄罗斯" width="120"></el-table-column>
                <el-table-column prop="leftRussiaThree" label="第三次离开俄罗斯" width="120"></el-table-column>
                <el-table-column prop="enterRussiaFour" label="第四次入境俄罗斯" width="120"></el-table-column>
                <el-table-column prop="leftRussiaFour" label="第四次离开俄罗斯" width="120"></el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="openTripDialog(2, scope)"
                        v-if="useName === '刘浩' || scope.row.process_status === useName"
                    >编辑</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 简化信息查看 (buttonDoe === 3) -->
            <!-- 简化信息查看 (buttonDoe === 3) -->
            <!-- 简化信息查看 (buttonDoe === 3) -->
            <div v-if="buttonDoe === 3">
              <el-table :data="simplifiedTripData" style="width: 100%" border>
                <el-table-column prop="number" label="工号" width="120"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="department" label="部门" width="120"></el-table-column>
                <el-table-column prop="business" label="签证" width="150"></el-table-column>
                <el-table-column prop="fare" label="费用" width="120"></el-table-column>
                <el-table-column prop="type" label="出入境类型" width="120"></el-table-column>
                <el-table-column prop="date" label="日期" width="120"></el-table-column>
              </el-table>
            </div>
            <!-- 月度停留统计 (buttonDoe === 4) -->
            <div v-if="buttonDoe === 4">
              <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="8">
                  <el-select v-model="selectedYear" placeholder="选择年份" @change="calculateMonthlyStay">
                    <el-option
                        v-for="year in availableYears"
                        :key="year"
                        :label="year + '年'"
                        :value="year">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="16" style="text-align: right;">
                  <el-button type="primary" @click="exportMonthlyStats">
                    导出Excel
                  </el-button>
                </el-col>
              </el-row>
              <el-table :data="monthlyStayData" style="width: 100%" border>
                <el-table-column prop="number" label="工号" width="120" fixed="left"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120" fixed="left"></el-table-column>
                <el-table-column prop="department" label="部门" width="120"></el-table-column>
                <el-table-column prop="section" label="科室" width="120"></el-table-column> <!-- 新增科室列 -->
                <el-table-column
                    v-for="month in 12"
                    :key="month"
                    :label="month + '月'"
                    width="100">
                  <template slot-scope="scope">
                    {{ scope.row[month] || 0 }}
                  </template>
                </el-table-column>
                <el-table-column prop="total" label="全年总计" width="100" fixed="right">
                  <template slot-scope="scope">
                    <strong>{{ scope.row.total }}天</strong>
                  </template>
                </el-table-column>
              </el-table>

            </div>
            <!-- 班车信息部分修改 -->
            <div v-if="buttonDoe === 5">
              <el-table
                  :data="filteredBusData"
                  style="width: 100%"
                  border
                  :default-sort="{prop: 'date', order: 'descending'}"
              >
                <el-table-column prop="number" label="工号" width="120" sortable></el-table-column>
                <el-table-column prop="name" label="姓名" width="120" sortable></el-table-column>
                <el-table-column prop="department" label="部门" width="120" sortable></el-table-column>
                <el-table-column
                    prop="business"
                    label="签证"
                    width="150"
                    sortable
                    :filters="businessFilters"
                    :filter-method="filterusiness"
                >
                </el-table-column>
                <el-table-column
                    prop="type"
                    label="出入境类型"
                    width="120"
                    :sortable="true"
                    :filters="typeFilters"
                    :filter-method="filterType"
                >
                </el-table-column>

                <el-table-column
                    prop="date"
                    label="日期"
                    width="180"
                    sortable
                >
                  <template slot-scope="scope">
                    <div>{{ scope.row.date }}</div>
                    <div :style="{ color: scope.row.daysDiff >= 0 ? '#67C23A' : '#F56C6C' }">
                      {{ scope.row.daysDiffText }}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="签证结束时间" width="120">
                  <template slot-scope="scope">
        <span v-if="scope.row.business === 'business' && scope.row.busineseBegan">
          {{ calculateVisaEndDate(scope.row.busineseBegan) }}
        </span>
                  </template>
                </el-table-column>

                <!-- 添加航班号填写列 -->
                <el-table-column label="航班号" width="150">
                  <template slot-scope="scope">
                    <el-input
                        v-model="scope.row.flightNumber"
                        placeholder="输入航班号"
                        size="small"
                        @change="updateFlightNumber(scope.row)"
                        :disabled="useName !== '刘浩'"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="buttonDoe === 6">
              <!-- 出差记录表格 (无操作按钮) -->
              <el-table :data="chineseTripData" style="width: 100%" border>
                <el-table-column prop="number" label="工号" width="120"></el-table-column>
                <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                <el-table-column prop="department" label="部门" width="120" sortable></el-table-column>
                <el-table-column prop="section" label="科室" width="120" sortable></el-table-column>
                <el-table-column prop="roomNumber" label="房间号码" width="120"></el-table-column>
                <el-table-column prop="phoneNumber" label="电话" width="120" sortable></el-table-column>
                <el-table-column prop="process_status" label="修改领导" width="120" sortable></el-table-column>
              </el-table>
            </div>
            <!-- 月度状态表 -->
            <div v-if="buttonDoe === 7">
              <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="8">
                  <el-select v-model="selectedStatusYear" placeholder="选择年份" style="margin-right: 10px;">
                    <el-option
                        v-for="year in statusYears"
                        :key="year"
                        :label="year + '年'"
                        :value="year">
                    </el-option>
                  </el-select>
                  <el-select v-model="selectedStatusMonth" placeholder="选择月份">
                    <el-option
                        v-for="month in statusMonths"
                        :key="month.value"
                        :label="month.label"
                        :value="month.value">
                    </el-option>
                  </el-select>
                  <el-button
                      type="primary"
                      @click="generateMonthlyStatus"
                      style="margin-left: 10px;">
                    生成状态表
                  </el-button>
                </el-col>
                <el-col :span="16" style="text-align: right;">
                  <el-button type="success" @click="exportMonthlyStatus">
                    导出Excel
                  </el-button>
                </el-col>
              </el-row>

              <!-- 月度状态表格 -->
              <!-- 修改月度状态表格部分 -->
              <!-- 修改月度状态表格部分 -->
              <div class="monthly-status-container" v-if="monthlyStatusData.length > 0">
                <div class="table-wrapper">
                  <table class="monthly-status-table" border="1">
                    <thead>
                    <tr>
                      <th rowspan="3" style="min-width: 100px; position: sticky; left: 0; background: #f5f7fa; z-index: 10;">姓名</th>
                      <th rowspan="3" style="min-width: 100px; position: sticky; left: 100px; background: #f5f7fa; z-index: 10;">部门</th>
                      <th rowspan="3" style="min-width: 100px; position: sticky; left: 200px; background: #f5f7fa; z-index: 10;">科室</th>
                      <th rowspan="3" style="min-width: 100px; position: sticky; left: 300px; background: #f5f7fa; z-index: 10;">签证类型</th>
                      <th :colspan="monthlyStatusHeaders.length" style="text-align: center; background: #e1f3d8;">
                        {{ selectedStatusYear }}年{{ selectedStatusMonth }}月 - 每日状态
                      </th>
                    </tr>
                    <tr>
                      <th v-for="header in monthlyStatusHeaders"
                          :key="header.date"
                          :style="getHeaderStyle(header)"
                          class="date-header">
                        <div class="date-display">{{ header.day }}</div>
                        <div class="weekday-display">{{ header.weekday }}</div>
                      </th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr v-for="employee in monthlyStatusData" :key="employee.number">
                      <td style="position: sticky; left: 0; background: white; font-weight: bold;">
                        {{ employee.name }}
                      </td>
                      <td style="position: sticky; left: 100px; background: white;">
                        {{ employee.department }}
                      </td>
                      <td style="position: sticky; left: 200px; background: white;">
                        {{ employee.section }}
                      </td>
                      <td style="position: sticky; left: 300px; background: white;">
                        {{ employee.business }}
                      </td>
                      <td v-for="header in monthlyStatusHeaders"
                          :key="header.date"
                          :style="getCellStyle(employee.status[header.date])"
                          :title="getCellTooltip(employee, header.date)"
                          class="status-cell">
                        {{ getStatusDisplay(employee.status[header.date]) }}
                      </td>
                    </tr>
                    </tbody>
                  </table>
                </div>
                <!-- 图例说明保持不变 -->
              </div>

              <div v-else style="text-align: center; padding: 50px; color: #909399;">
                <i class="el-icon-data-analysis" style="font-size: 48px; margin-bottom: 16px;"></i>
                <div>请选择年份和月份，然后点击"生成状态表"</div>
              </div>
            </div>


          </el-main>
        </el-container>
      </el-container>
    </el-container>

    <!-- 出差管理弹窗 -->
    <el-dialog
        :title="tripDoe === 1 ? '添加出差记录' : '编辑出差记录'"
        :visible.sync="tripDialogVisible"
        width="60%">
      <el-form label-width="140px" :model="tripForm">
        <el-form-item label="工号">
          <el-input v-model="tripForm.number" :disabled="tripDoe === 2"></el-input>
        </el-form-item>

        <!-- 添加时显示姓名，编辑时不显示 -->
        <el-form-item label="姓名" >
          <el-input v-model="tripForm.name" :disabled="tripDoe === 2"></el-input>
        </el-form-item>

        <el-form-item label="部门">
          <el-input v-model="tripForm.department" :disabled="tripDoe === 2"></el-input>
        </el-form-item>
        <el-form-item label="科室">
          <el-input v-model="tripForm.section" :disabled="tripDoe === 2"></el-input>
        </el-form-item>
        <el-form-item label="性别" v-if="tripDoe === 2">
          <el-select v-model="tripForm.gender" placeholder="请选择性别" disabled>
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费用" v-if="tripDoe === 2">
          <el-input v-model="tripForm.fare" ></el-input>
        </el-form-item>
        <el-form-item label="护照号码" v-if="tripDoe === 2">
          <el-input v-model="tripForm.passportNumber"
                    :readonly="useName !== '刘浩'"></el-input>
        </el-form-item>
        <el-form-item label="签证" v-if="tripDoe === 2">
          <el-input v-model="tripForm.business"
                    :readonly="useName !== '刘浩'"></el-input>
        </el-form-item>
        <el-form-item label="签证开始时间">
          <el-date-picker
              v-model="tripForm.busineseBegan" v-if="useName === this.useName&&'刘浩'"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>

        <!-- 四次出入境时间 -->
        <el-form-item label="第一次入境俄罗斯" prop="enterRussiaOne" :rules="[{ required: true, message: '请选择第一次入境俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.enterRussiaOne"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="business === 'business' ? enterRussiaOnePickerOptions : {}"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第一次离开俄罗斯" prop="leftRussiaOne" :rules="[{ required: true, message: '请选择第一次离开俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.leftRussiaOne"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="leftRussiaOnePickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <div v-if="tripForm.enterRussiaOne && tripForm.leftRussiaOne" style="margin-bottom: 20px;">
          <span>第一次在俄罗斯停留: {{ calculateDaysInRussia(tripForm.enterRussiaOne, tripForm.leftRussiaOne) }} 天</span>
        </div>

        <el-form-item label="第二次入境俄罗斯" prop="enterRussiaTwo" :rules="[{ required: true, message: '请选择第二次入境俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.enterRussiaTwo"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="enterRussiaTwoPickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第二次离开俄罗斯" prop="leftRussiaTwo" :rules="[{ required: true, message: '请选择第二次离开俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.leftRussiaTwo"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="leftRussiaTwoPickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <div v-if="tripForm.enterRussiaTwo && tripForm.leftRussiaTwo" style="margin-bottom: 20px;">
          <span>第二次在俄罗斯停留: {{ calculateDaysInRussia(tripForm.enterRussiaTwo, tripForm.leftRussiaTwo) }} 天</span>
        </div>
        <el-form-item label="第三次入境俄罗斯" prop="enterRussiaThree" :rules="[{ required: true, message: '请选择第三次入境俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.enterRussiaThree"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="enterRussiaThreePickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第三次离开俄罗斯" prop="leftRussiaThree" :rules="[{ required: true, message: '请选择第三次离开俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.leftRussiaThree"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="leftRussiaThreePickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <div v-if="tripForm.enterRussiaThree && tripForm.leftRussiaThree" style="margin-bottom: 20px;">
          <span>第三次在俄罗斯停留: {{ calculateDaysInRussia(tripForm.enterRussiaThree, tripForm.leftRussiaThree) }} 天</span>
        </div>

        <el-form-item label="第四次入境俄罗斯" prop="enterRussiaFour" :rules="[{ required: true, message: '请选择第四次入境俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.enterRussiaFour"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="enterRussiaFourPickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第四次离开俄罗斯" prop="leftRussiaFour" :rules="[{ required: true, message: '请选择第四次离开俄罗斯日期', trigger: 'blur' }]">
          <el-date-picker
              v-model="tripForm.leftRussiaFour"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="leftRussiaFourPickerOptions"
              @change="validateDates">
          </el-date-picker>
        </el-form-item>
        <div v-if="tripForm.enterRussiaFour && tripForm.leftRussiaFour" style="margin-bottom: 20px;">
          <span>第四次在俄罗斯停留: {{ calculateDaysInRussia(tripForm.enterRussiaFour, tripForm.leftRussiaFour) }} 天</span>
        </div>

      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="tripDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="editorTripOk">确定</el-button>
  </span>



    </el-dialog>

    <!-- Excel上传对话框 -->
    <el-dialog
        title="上传Excel文档"
        :visible.sync="excelUploadDialogVisible"
        width="40%">
      <div class="upload-area" @click="$refs.upload.click()">
        <div v-if="!selectedFile">
          <i class="el-icon-upload upload-icon"></i>
          <div>点击或拖拽文件到此处上传</div>
          <div class="el-upload__text">支持Excel文件，大小不超过10MB</div>
        </div>
        <div v-else>
          <div>已选择文件:  selectedFile.name </div>
          <el-button
              type="text"
              @click.stop="selectedFile = null; $refs.upload.value = ''">
            重新选择
          </el-button>
        </div>
        <input
            type="file"
            ref="upload"
            style="display: none"
            accept=".xlsx,.xls"
            @change="handleExcelFileChange">
      </div>

      <div v-if="uploadResult" style="margin-top: 20px;">
        <el-alert
            :title="`导入结果: 成功 ${uploadResult.success} 条, 失败 ${uploadResult.fail} 条`"
            :type="uploadResult.fail > 0 ? 'warning' : 'success'"
            show-icon>
        </el-alert>

        <div v-if="uploadResult.failDetails && uploadResult.failDetails.length > 0"
             style="margin-top: 10px; max-height: 200px; overflow-y: auto;">
          <div style="font-weight: bold; margin-bottom: 5px;">失败详情:</div>
          <el-table
              :data="uploadResult.failDetails"
              size="mini"
              border
              style="width: 100%">
            <el-table-column prop="row" label="行号" width="80"></el-table-column>
            <el-table-column prop="reason" label="失败原因"></el-table-column>
          </el-table>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeExcelUploadDialog">取消</el-button>
        <el-button
            type="primary"
            @click="submitExcelUpload"
            :loading="uploadLoading">
           uploadLoading ? '上传中...' : '开始上传'
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import * as XLSX from 'xlsx';

export default {
  name: "TripManagement",
  data() {
    return {






      cancelSwitch: false, // 开关状态，false表示cancel=0，true表示cancel=1
      switchLoading: false, // 开关按钮的加载状态


      enterRussiaOnePickerOptions: {},
      leftRussiaOnePickerOptions: {},
      enterRussiaTwoPickerOptions: {},
      leftRussiaTwoPickerOptions: {},
      enterRussiaThreePickerOptions: {},
      leftRussiaThreePickerOptions: {},
      enterRussiaFourPickerOptions: {},
      leftRussiaFourPickerOptions: {},
      dateErrors: [],

      typeFilters: [
        { text: '入俄罗斯', value: '入俄罗斯' },
        { text: '出俄罗斯', value: '出俄罗斯' },
      ],
      businessFilters: [
        { text: 'business', value: 'business' },
        { text: 'work', value: 'work' },
      ],
      monthlyStatusDialogVisible: false,
      selectedStatusYear: new Date().getFullYear(),
      selectedStatusMonth: new Date().getMonth() + 1,
      monthlyStatusData: [],
      monthlyStatusHeaders: [],
      statusYears: [2024, 2025, 2026, 2027],
      statusMonths: [
        { value: 1, label: '1月' },
        { value: 2, label: '2月' },
        { value: 3, label: '3月' },
        { value: 4, label: '4月' },
        { value: 5, label: '5月' },
        { value: 6, label: '6月' },
        { value: 7, label: '7月' },
        { value: 8, label: '8月' },
        { value: 9, label: '9月' },
        { value: 10, label: '10月' },
        { value: 11, label: '11月' },
        { value: 12, label: '12月' }
      ],
      monthlyStayData: [],
      selectedYear: new Date().getFullYear(),
      availableYears: [2025, 2026, 2027],

      simplifiedTripData: [],
      excelUploadDialogVisible: false,
      fileList: [],
      uploadLoading: false,
      uploadResult: null,
      selectedFile: null,
      tripDialogVisible: false,
      chineseTripData: [],
      tripForm: {
        number: '',
        create_time: '',
        update_time: '',
        creator: '',
        process_status: '',
        sys_update_user: '',
        sys_audit_user: '',
        sys_audit_time: '',
        sys_deleted: 0,
        name: '',
        department: '',
        section: '',
        gender: '',
        fare: '',
        passportNumber: '',
        business: '',
        busineseBegan: '',
        enterRussiaOne: '',
        leftRussiaOne: '',
        enterRussiaTwo: '',
        leftRussiaTwo: '',
        enterRussiaThree: '',
        leftRussiaThree: '',
        enterRussiaFour: '',
        leftRussiaFour: '',
        flightNumber: '',
        phoneNumber: '',
        roomNumber: '',
        cancel: '',
        birthDate: '',

      },
      tripDoe: "",
      tripScope: null,
      useName: '',
      useId: '',
      activeButton: 1,
      buttonDoe: 1,
    }
  },


  methods: {
    calculateVisaEndDate(startDateStr) {
      if (!startDateStr) return '';

      try {
        const startDate = new Date(startDateStr);
        if (isNaN(startDate.getTime())) return '';

        // 添加89天（89天包含开始当天，所以总共是89天）
        const endDate = new Date(startDate);
        endDate.setDate(endDate.getDate() + 88); // 因为包含开始当天，所以加88天得到第89天

        // 格式化日期为 yyyy-MM-dd
        const year = endDate.getFullYear();
        const month = String(endDate.getMonth() + 1).padStart(2, '0');
        const day = String(endDate.getDate()).padStart(2, '0');

        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error('计算签证结束日期错误:', e);
        return '';
      }
    },
    // 生成月度状态表
    generateMonthlyStatus() {
      if (!this.selectedStatusYear || !this.selectedStatusMonth) {
        this.$message.warning('请选择年份和月份');
        return;
      }

      // 生成表头（日期）
      this.generateMonthlyHeaders();

      // 生成员工状态数据
      this.generateEmployeeStatus();
    },

// 生成月度表头
    generateMonthlyHeaders() {
      const year = this.selectedStatusYear;
      const month = this.selectedStatusMonth;

      // 获取该月的天数
      const daysInMonth = new Date(year, month, 0).getDate();

      this.monthlyStatusHeaders = [];

      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month - 1, day);
        const weekday = date.getDay(); // 0=周日, 1=周一, ..., 6=周六

        this.monthlyStatusHeaders.push({
          date: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
          day: day,
          weekday: this.getChineseWeekday(weekday),
          isWeekend: weekday === 0 || weekday === 6
        });
      }
    },

// 获取中文星期
    getChineseWeekday(weekday) {
      const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
      return weekdays[weekday];
    },

// 生成员工状态数据
// 生成员工状态数据
    generateEmployeeStatusOne() {
      this.monthlyStatusData = [];

      // 先对数据进行排序（按科室和姓名）
      const sortedEmployees = [...this.chineseTripData].sort((a, b) => {
        // 首先按科室排序
        if (a.section && b.section) {
          const sectionCompare = a.section.localeCompare(b.section);
          if (sectionCompare !== 0) return sectionCompare;
        }
        // 然后按姓名排序
        return a.name.localeCompare(b.name);
      });

      sortedEmployees.forEach(employee => {
        const employeeStatus = {
          number: employee.number,
          name: employee.name,
          department: employee.department,
          section: employee.section, // 添加科室字段
          business: employee.business,
          status: {}
        };

        // 初始化所有日期状态为"在中国"
        this.monthlyStatusHeaders.forEach(header => {
          employeeStatus.status[header.date] = {
            location: 'china',
            isTransition: false,
            isWeekend: header.isWeekend,
            business: employee.business
          };
        });

        // 处理四次出入境记录
        for (let i = 1; i <= 4; i++) {
          const enterField = `enterRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;
          const leaveField = `leftRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;

          const entryDate = employee[enterField];
          const exitDate = employee[leaveField];

          if (entryDate && exitDate) {
            this.markRussiaPeriod(employeeStatus, entryDate, exitDate, employee.business);
          }
        }

        this.monthlyStatusData.push(employeeStatus);
      });
    },

// 标记俄罗斯期间
    markRussiaPeriod(employeeStatus, entryDate, exitDate, business) {
      const entry = new Date(entryDate);
      const exit = new Date(exitDate);

      this.monthlyStatusHeaders.forEach(header => {
        const currentDate = new Date(header.date);

        if (currentDate >= entry && currentDate <= exit) {
          const isEntryDay = currentDate.getTime() === entry.getTime();
          const isExitDay = currentDate.getTime() === exit.getTime();

          employeeStatus.status[header.date] = {
            location: 'russia',
            isTransition: isEntryDay || isExitDay,
            isWeekend: header.isWeekend,
            business: business // 保留 business 信息
          };
        }
      });
    },

// 获取表头样式
    getHeaderStyle(header) {
      const baseStyle = {
        minWidth: '40px',
        textAlign: 'center',
        padding: '4px 2px',
        fontSize: '12px'
      };

      if (header.isWeekend) {
        baseStyle.background = '#fff2f2';
        baseStyle.fontWeight = 'bold';
      }

      return baseStyle;
    },

// 获取单元格样式
    getCellStyle(status) {
      const style = {
        minWidth: '40px',
        height: '30px',
        textAlign: 'center',
        padding: '0',
        fontSize: '10px',
        cursor: 'pointer'
      };

      if (status.location === 'china') {
        style.background = status.isWeekend ? '#fed' : '#f56c6c'; // 中国周末浅黄，平时红色
        if (status.isWeekend) {
          style.border = '2px solid #333';
        }
      } else {
        style.background = status.isWeekend ? '#e6f7ff' : '#409EFF'; // 俄罗斯周末浅蓝，平时蓝色
        if (status.isWeekend) {
          style.border = '2px solid #333';
        }
      }

      if (status.isTransition) {
        style.background = '#67c23a'; // 出入境当天绿色
        style.fontWeight = 'bold';
      }

      return style;
    },

// 获取单元格显示内容
    getStatusDisplay(status) {
      if (status.isTransition) {
        return '转';
      }
      return status.location === 'china' ? '中' : '俄';
    },

// 获取单元格提示信息
// 获取单元格提示信息 - 显示俄罗斯周期
// 获取单元格提示信息 - 显示俄罗斯周期


// 新增方法：获取指定日期所在的俄罗斯周期
// 获取指定日期所在的俄罗斯周期（修复版）
    getCurrentRussiaPeriod(employee, targetDate) {
      const target = new Date(targetDate);

      // 检查四次出入境记录
      for (let i = 1; i <= 4; i++) {
        const enterField = `enterRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;
        const leaveField = `leftRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;

        const entryDate = employee[enterField];
        const exitDate = employee[leaveField];

        if (entryDate && exitDate) {
          const entry = new Date(entryDate);
          const exit = new Date(exitDate);

          // 检查目标日期是否在这个周期内
          if (target >= entry && target <= exit) {
            return {
              entry: this.formatDisplayDate(entryDate),
              exit: this.formatDisplayDate(exitDate),
              period: i // 第几次出入境
            };
          }
        }
      }

      return null;
    },

// 获取单元格提示信息（修复版）
    getCellTooltip(employee, date) {
      const status = employee.status[date];
      const locationText = status.location === 'china' ? '在中国' : '在俄罗斯';
      const transitionText = status.isTransition ? ' (出入境当天)' : '';
      const weekendText = status.isWeekend ? ' (周末)' : '';

      // 添加俄罗斯周期信息
      let periodInfo = '';
      if (status.location === 'russia') {
        const currentPeriod = this.getCurrentRussiaPeriod(employee, date);
        if (currentPeriod) {
          periodInfo = `\n俄罗斯周期(第${currentPeriod.period}次): ${currentPeriod.entry} 至 ${currentPeriod.exit}`;
        }
      }

      return `${employee.name} - ${date}\n状态: ${locationText}${transitionText}${weekendText}${periodInfo}`;
    },

// 格式化日期显示（去掉时间部分）
    formatDisplayDate(dateString) {
      if (!dateString) return '';
      return dateString.split(' ')[0]; // 只取日期部分，去掉时间
    },

// 导出月度状态表到Excel
    exportMonthlyStatus() {
      if (!this.monthlyStatusData.length) {
        this.$message.warning('没有数据可导出');
        return;
      }

      try {
        const wb = XLSX.utils.book_new();

        // 准备表头
        const headers = ['姓名', '部门'];
        this.monthlyStatusHeaders.forEach(header => {
          headers.push(`${header.day}日(${header.weekday})`);
        });

        // 准备数据
        const excelData = [headers];

        this.monthlyStatusData.forEach(employee => {
          const row = [employee.name, employee.department];

          this.monthlyStatusHeaders.forEach(header => {
            const status = employee.status[header.date];
            row.push(status.location === 'china' ? '中国' : '俄罗斯');
          });

          excelData.push(row);
        });

        const ws = XLSX.utils.aoa_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, '月度状态表');

        const filename = `${this.selectedStatusYear}年${this.selectedStatusMonth}月员工状态表.xlsx`;
        XLSX.writeFile(wb, filename);

        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出Excel失败:', error);
        this.$message.error('导出失败');
      }
    },
    // 导出全部数据到Excel
    async exportAllData() {
      if (!this.chineseTripData || this.chineseTripData.length === 0) {
        this.$message.warning('没有数据可导出');
        return;
      }

      try {
        const wb = XLSX.utils.book_new();

        // 准备表头
        const headers = [
          '工号', '姓名', '部门', '科室', '性别', '费用', '护照号码', '签证',
          '签证开始时间', '第一次入境俄罗斯', '第一次离开俄罗斯',
          '第二次入境俄罗斯', '第二次离开俄罗斯', '第三次入境俄罗斯',
          '第三次离开俄罗斯', '第四次入境俄罗斯', '第四次离开俄罗斯',
          '航班号', '手机号', '房间号', '取消状态', '出生日期',
          '创建时间', '更新时间', '创建人', '处理状态', '系统更新用户',
          '系统审核用户', '系统审核时间', '系统删除标记'
        ];

        // 准备数据
        const excelData = [headers];

        this.chineseTripData.forEach(item => {
          const row = [
            item.number, item.name, item.department, item.section, item.gender,
            item.fare, item.passportNumber, item.business, item.busineseBegan,
            item.enterRussiaOne, item.leftRussiaOne, item.enterRussiaTwo,
            item.leftRussiaTwo, item.enterRussiaThree, item.leftRussiaThree,
            item.enterRussiaFour, item.leftRussiaFour, item.flightNumber,
            item.phoneNumber, item.roomNumber, item.cancel, item.birthDate,
            item.create_time, item.update_time, item.creator, item.process_status,
            item.sys_update_user, item.sys_audit_user, item.sys_audit_time,
            item.sys_deleted
          ];
          excelData.push(row);
        });

        const ws = XLSX.utils.aoa_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, '全部出差记录');

        // 生成文件名
        const now = new Date();
        const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
        const filename = `全部出差记录_${timestamp}.xlsx`;

        XLSX.writeFile(wb, filename);

        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出Excel失败:', error);
        this.$message.error('导出失败');
      }
    },

// 修改 updateFlightNumber 方法
    async updateFlightNumber(row) {
      if (this.useName !== '刘浩') {
        this.$message.warning('您没有权限执行此操作');
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: '正在更新航班号...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 找到原始记录
        const originalRecord = this.chineseTripData.find(item => item.number === row.number);
        if (!originalRecord) {
          throw new Error('未找到原始记录');
        }

        // 构建更新数据，保留所有原始字段
        const updateData = {
          id: originalRecord.id,
          number: originalRecord.number,
          name: originalRecord.name,
          department: originalRecord.department,
          section: originalRecord.section,
          gender: originalRecord.gender,
          fare: originalRecord.fare,
          passportNumber: originalRecord.passportNumber,
          business: originalRecord.business,
          busineseBegan: originalRecord.busineseBegan,
          enterRussiaOne: originalRecord.enterRussiaOne,
          leftRussiaOne: originalRecord.leftRussiaOne,
          enterRussiaTwo: originalRecord.enterRussiaTwo,
          leftRussiaTwo: originalRecord.leftRussiaTwo,
          enterRussiaThree: originalRecord.enterRussiaThree,
          leftRussiaThree: originalRecord.leftRussiaThree,
          enterRussiaFour: originalRecord.enterRussiaFour,
          leftRussiaFour: originalRecord.leftRussiaFour,
          flightNumber: row.flightNumber || originalRecord.flightNumber, // 只更新航班号
          phoneNumber: originalRecord.phoneNumber,
          roomNumber: originalRecord.roomNumber,
          cancel: originalRecord.cancel,
          birthDate: originalRecord.birthDate,
          create_time: originalRecord.create_time,
          update_time: new Date().toISOString(),
          creator: originalRecord.creator,
          process_status: originalRecord.process_status,
          sys_update_user: this.useName,
          sys_audit_user: originalRecord.sys_audit_user,
          sys_audit_time: originalRecord.sys_audit_time,
          sys_deleted: originalRecord.sys_deleted
        };

        console.log('发送航班号更新数据:', updateData);
        const result = await this.$request.post('/editChineseTrip', updateData);

        if (result && (result.code === 200 || result.msg === 'success')) {
          this.$message.success("航班号更新成功");
          // 直接更新本地数据，避免重新查询
          this.updateLocalFlightNumber(row.number, row.flightNumber);
        } else {
          throw new Error(result.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新航班号失败:', error);
        this.$message.error(`更新失败: ${error.message}`);
        // 恢复原始数据
        await this.queryAllChineseTrip();
      } finally {
        loading.close();
      }
    },

// 新增方法：通过number更新本地数据
    updateLocalDataByNumber(number, updateFields) {
      // 更新 chineseTripData
      const tripRecord = this.chineseTripData.find(item => item.number === number);
      if (tripRecord) {
        Object.assign(tripRecord, updateFields);
      }

      // 更新 simplifiedTripData 中所有匹配的记录
      this.simplifiedTripData.forEach(item => {
        if (item.number === number) {
          Object.assign(item, updateFields);
        }
      });

      // 更新 monthlyStayData
      const monthlyRecord = this.monthlyStayData.find(item => item.number === number);
      if (monthlyRecord && updateFields.name) {
        monthlyRecord.name = updateFields.name;
      }

      // 强制更新视图
      this.$forceUpdate();
    },

// 如果需要，可以添加一个通用的通过number更新的方法
    async updateRecordByNumber(number, updateData) {
      const loading = this.$loading({
        lock: true,
        text: '正在更新数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        const completeUpdateData = {
          number: number,
          ...updateData,
          update_time: new Date().toISOString(),
          sys_update_user: this.useName
        };

        const result = await this.$request.post('/editChineseTrip', completeUpdateData);

        if (result && (result.code === 200 || result.msg === 'success')) {
          this.$message.success("更新成功");
          this.updateLocalDataByNumber(number, updateData);
          return true;
        } else {
          throw new Error(result.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新失败:', error);
        this.$message.error(`更新失败: ${error.message}`);
        await this.queryAllChineseTrip(); // 失败时重新查询
        return false;
      } finally {
        loading.close();
      }
    },

// 如果需要编辑其他字段，可以这样使用：
    async editOtherField(number, fieldName, value) {
      return await this.updateRecordByNumber(number, { [fieldName]: value });
    },

// 更新本地数据，避免重新查询所有数据
    updateLocalFlightNumber(number, flightNumber) {
      // 更新 chineseTripData 中的航班号
      const record = this.chineseTripData.find(item => item.number === number);
      if (record) {
        record.flightNumber = flightNumber;
      }

      // 更新 simplifiedTripData 中的航班号
      this.simplifiedTripData.forEach(item => {
        if (item.number === number) {
          item.flightNumber = flightNumber;
        }
      });

      // 更新 monthlyStayData 中的航班号（如果需要）
      // 注意：monthlyStayData 通常不包含航班号，所以可能不需要

      // 强制更新视图
      this.$forceUpdate();
    },



    async toggleCancelStatus() {
      if (this.useName !== '刘浩') return;

      this.switchLoading = true;
      try {
        const newStatus = this.cancelSwitch ? '0' : '1';
        const requests = this.chineseTripData.map(item =>
            this.$request.post('/editChineseTrip', {
              ...item,
              cancel: newStatus,
              sys_update_user: this.useName
            })
        );

        await Promise.all(requests);
        this.$message.success(`成功更新所有记录状态为 ${newStatus}`);
        this.cancelSwitch = !this.cancelSwitch;
        await this.queryAllChineseTrip();
      } catch (error) {
        console.error('更新状态失败:', error);
        this.$message.error('更新状态失败');
      } finally {
        this.switchLoading = false;
      }
    },

    calculateDaysInRussia(enterDate, leaveDate) {
      if (!enterDate || !leaveDate) return 0;

      const enter = new Date(enterDate);
      const leave = new Date(leaveDate);
      const timeDiff = leave.getTime() - enter.getTime();
      return Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1; // 包含首尾两天
    },
    validateDates() {
      this.dateErrors = [];
      const dates = [
        { enter: 'enterRussiaOne', leave: 'leftRussiaOne', name: '第一次' },
        { enter: 'enterRussiaTwo', leave: 'leftRussiaTwo', name: '第二次' },
        { enter: 'enterRussiaThree', leave: 'leftRussiaThree', name: '第三次' },
        { enter: 'enterRussiaFour', leave: 'leftRussiaFour', name: '第四次' }
      ];

      // 检查必填
      dates.forEach(item => {
        if (!this.tripForm[item.enter] || !this.tripForm[item.leave]) {
          this.dateErrors.push(`${item.name}出入境日期必须填写`);
        }
      });

      if (this.dateErrors.length > 0) return false;

      // 检查日期顺序和重复
      const allDates = [];
      dates.forEach(item => {
        if (this.tripForm[item.enter] && this.tripForm[item.leave]) {
          // 检查入境日期是否早于离境日期
          if (new Date(this.tripForm[item.enter]) > new Date(this.tripForm[item.leave])) {
            this.dateErrors.push(`${item.name}入境日期不能晚于离境日期`);
          }

          // 添加到所有日期数组用于重复检查
          allDates.push({ date: this.tripForm[item.enter], type: `${item.name}入境` });
          allDates.push({ date: this.tripForm[item.leave], type: `${item.name}离境` });
        }
      });

      // 检查日期重复
      const dateMap = {};
      allDates.forEach(item => {
        if (dateMap[item.date]) {
          dateMap[item.date].push(item.type);
        } else {
          dateMap[item.date] = [item.type];
        }
      });

      for (const date in dateMap) {
        if (dateMap[date].length > 1) {
          this.dateErrors.push(`日期 ${date} 重复用于: ${dateMap[date].join(' 和 ')}`);
        }
      }

      // 检查business=business时的89天限制
      if (this.tripForm.business === 'business') {
        dates.forEach(item => {
          if (this.tripForm[item.enter] && this.tripForm[item.leave]) {
            const days = this.calculateDaysInRussia(this.tripForm[item.enter], this.tripForm[item.leave]);
            if (days > 89) {
              this.dateErrors.push(`${item.name}在俄罗斯停留${days}天，超过89天限制`);
            }
          }
        });
      } else if (this.tripForm.business === 'work') {  // 注意 'wok' 的条件
        dates.forEach(item => {
          if (this.tripForm[item.enter] && this.tripForm[item.leave]) {
            const days = this.calculateDaysInRussia(this.tripForm[item.enter], this.tripForm[item.leave]);
            if (days < 120) {  // 对 'wok' 的限制为 120 天
              this.dateErrors.push(`${item.name}在俄罗斯停留${days}天，需要大于120天`);
            }
          }
        });
      }


      // 更新日期选择器的限制
      this.updateDatePickerOptions();

      return this.dateErrors.length === 0;
    },

    // 更新日期选择器的限制
    updateDatePickerOptions() {
      // 第一次入境日期限制：不能晚于第一次离境日期
      if (this.tripForm.leftRussiaOne) {
        this.enterRussiaOnePickerOptions = {
          disabledDate: (time) => {
            return time.getTime() > new Date(this.tripForm.leftRussiaOne).getTime();
          }
        };
      }

      // 第一次离境日期限制：不能早于第一次入境日期
      if (this.tripForm.enterRussiaOne) {
        this.leftRussiaOnePickerOptions = {
          disabledDate: (time) => {
            return time.getTime() < new Date(this.tripForm.enterRussiaOne).getTime();
          }
        };

        // 如果是business签证，限制最多89天后
        if (this.tripForm.business === 'business') {
          const maxDate = new Date(this.tripForm.enterRussiaOne);
          maxDate.setDate(maxDate.getDate() + 88); // 89天包含第一天
          this.leftRussiaOnePickerOptions.disabledDate = (time) => {
            return time.getTime() < new Date(this.tripForm.enterRussiaOne).getTime() ||
                time.getTime() > maxDate.getTime();
          };
        }




      }

      // 第二次入境日期限制：不能早于第一次离境日期，不能晚于第二次离境日期
      if (this.tripForm.leftRussiaOne && this.tripForm.leftRussiaTwo) {
        this.enterRussiaTwoPickerOptions = {
          disabledDate: (time) => {
            return time.getTime() <= new Date(this.tripForm.leftRussiaOne).getTime() ||
                (this.tripForm.leftRussiaTwo && time.getTime() > new Date(this.tripForm.leftRussiaTwo).getTime());
          }
        };
      }

      // 第二次离境日期限制：不能早于第二次入境日期
      if (this.tripForm.enterRussiaTwo) {
        this.leftRussiaTwoPickerOptions = {
          disabledDate: (time) => {
            return time.getTime() < new Date(this.tripForm.enterRussiaTwo).getTime();
          }
        };
      }

      // 类似地更新第三次和第四次的日期选择器限制...
    },
    filterType(value, row) {
      return row.type === value;
    },
    businessType(value, row) {
      return row.business === value;
    },

// 计算月度停留天数
// 计算月度停留天数（修复版）
    calculateMonthlyStay() {
      if (!this.selectedYear) {
        this.$message.warning('请选择年份');
        return;
      }

      this.monthlyStayData = [];

      // 先对数据进行排序（按科室和姓名）
      const sortedEmployees = [...this.chineseTripData].sort((a, b) => {
        // 首先按科室排序
        if (a.section && b.section) {
          const sectionCompare = a.section.localeCompare(b.section);
          if (sectionCompare !== 0) return sectionCompare;
        }
        // 然后按姓名排序
        return a.name.localeCompare(b.name);
      });

      sortedEmployees.forEach(employee => {
        const monthlyStats = {
          number: employee.number,
          name: employee.name,
          department: employee.department,
          section: employee.section, // 添加科室字段
          total: 0
        };

        // 初始化12个月的数据
        for (let month = 1; month <= 12; month++) {
          monthlyStats[month] = 0;
        }

        // 处理四次出入境记录
        for (let i = 1; i <= 4; i++) {
          const enterField = `enterRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;
          const leaveField = `leftRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;

          const entryDate = employee[enterField];
          const exitDate = employee[leaveField];

          if (entryDate && exitDate) {
            // 使用新的精确计算方法
            const days = this.calculateExactDaysInMonth(entryDate, exitDate, this.selectedYear);

            // 累加每个月的天数
            for (let month = 1; month <= 12; month++) {
              monthlyStats[month] += days[month] || 0;
              monthlyStats.total += days[month] || 0;
            }
          }
        }

        this.monthlyStayData.push(monthlyStats);
      });

      console.log('月度停留统计:', this.monthlyStayData);
    },

// 精确计算在指定年份中各月的停留天数（包含入境当天和离境当天）
    calculateExactDaysInMonth(entryDateStr, exitDateStr, year) {
      const monthlyDays = {};

      try {
        const entryDate = new Date(entryDateStr);
        const exitDate = new Date(exitDateStr);

        // 确保日期有效
        if (isNaN(entryDate.getTime()) || isNaN(exitDate.getTime())) {
          return monthlyDays;
        }

        // 只处理指定年份的数据
        if (exitDate.getFullYear() < year || entryDate.getFullYear() > year) {
          return monthlyDays;
        }

        // 遍历从入境到离境的每一天（包含首尾）
        const currentDate = new Date(entryDate);
        while (currentDate <= exitDate) {
          const currentYear = currentDate.getFullYear();
          const currentMonth = currentDate.getMonth() + 1; // 月份从1开始

          // 只统计指定年份的数据
          if (currentYear === year) {
            if (!monthlyDays[currentMonth]) {
              monthlyDays[currentMonth] = 0;
            }
            monthlyDays[currentMonth]++;
          }

          // 移动到下一天
          currentDate.setDate(currentDate.getDate() + 1);
        }
      } catch (error) {
        console.error('计算停留天数错误:', error);
      }

      return monthlyDays;
    },

// 保留原有的简化计算方法，但使用新的精确计算方法
    calculateDaysInMonth(entryDateStr, exitDateStr, year) {
      return this.calculateExactDaysInMonth(entryDateStr, exitDateStr, year);
    },
// 导出月度统计到Excel
    exportMonthlyStats() {
      if (!this.monthlyStayData.length) {
        this.$message.warning('没有数据可导出');
        return;
      }

      try {
        const wb = XLSX.utils.book_new();

        // 准备表头
        const headers = ['工号', '姓名', '部门'];
        for (let month = 1; month <= 12; month++) {
          headers.push(`${month}月`);
        }
        headers.push('全年总计');

        // 准备数据
        const excelData = [headers];

        this.monthlyStayData.forEach(employee => {
          const row = [
            employee.number,
            employee.name,
            employee.department
          ];

          for (let month = 1; month <= 12; month++) {
            row.push(employee[month] || 0);
          }

          row.push(employee.total || 0);
          excelData.push(row);
        });

        const ws = XLSX.utils.aoa_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, `${this.selectedYear}年月度停留统计`);
        XLSX.writeFile(wb, `${this.selectedYear}年员工俄罗斯停留统计.xlsx`);

        this.$message.success('导出成功');
      } catch (error) {
        console.error('导出Excel失败:', error);
        this.$message.error('导出失败');
      }
    },
    canEditRecord(record) {
      // 刘浩可以编辑所有记录
      if (this.useName === '刘浩') {
        return true;
      }
      // 其他用户只能编辑自己创建的记录
      return record.process_status === this.useName && record.cancel === '0';
    },

    // 生成简化版出差数据（只显示月份）
    // 生成简化版出差数据（显示每次出入境的年月）
// 生成简化版出差数据（显示每次出入境的年月）
    generateSimplifiedData() {
      this.simplifiedTripData = [];

      this.chineseTripData.forEach(item => {
        for (let i = 1; i <= 4; i++) {
          const enterField = `enterRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;
          const leaveField = `leftRussia${i === 1 ? 'One' : i === 2 ? 'Two' : i === 3 ? 'Three' : 'Four'}`;

          const enter = item[enterField];
          const leave = item[leaveField];

          if (enter) {
            this.simplifiedTripData.push({
              number: item.number,
              name: item.name,
              department: item.department,
              business: item.business,
              fare: item.fare,
              type: '入俄罗斯',
              date: this.formatDate(enter),
              flightNumber: item.flightNumber || '',
              busineseBegan: item.busineseBegan, // 添加签证开始时间
              // 添加其他可能需要的基础字段
              passportNumber: item.passportNumber,
              phoneNumber: item.phoneNumber,
              roomNumber: item.roomNumber
            });
          }
          if (leave) {
            this.simplifiedTripData.push({
              number: item.number,
              name: item.name,
              department: item.department,
              business: item.business,
              fare: item.fare,
              type: '出俄罗斯',
              date: this.formatDate(leave),
              flightNumber: item.flightNumber || '',
              busineseBegan: item.busineseBegan, // 添加签证开始时间
              // 添加其他可能需要的基础字段
              passportNumber: item.passportNumber,
              phoneNumber: item.phoneNumber,
              roomNumber: item.roomNumber
            });
          }
        }
      });
    },

// 格式化日期为年月（yyyy-MM）
    formatDate(dateString) {
      if (!dateString) return '';

      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
          // 如果不是有效日期，尝试直接解析格式为yyyy-MM-dd的字符串
          if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
            return dateString;
          }
          return '';
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error('日期格式化错误:', e);
        return '';
      }
    },
    inquiry() {
      //输入用户编号，向后端查询信息
      const useId = localStorage.getItem('userName').replace(/"/g, '');
      this.$request.post('/useQueryPower', {
        queryFiledName: 'goodProductCondition',
        userId: useId,
      }).then(result => {
        if (result.code === 401) {
          this.$router.push('UserLogin')
          alert("您未登录，请登录")
        } else {
          this.useName = result.data.name
          this.usePower = result.data.goodProductCondition
          this.useId = useId
        }
      })
    },
    // 出差管理相关方法
    async queryAllChineseTrip() {
      try {
        const result = await this.$request.post('/queryAllChineseTrip');
        if (result.code === 401) {
          this.$router.push('UserLogin');
          this.$message.error("您未登录，请登录");
        } else {
          this.chineseTripData = result.data || [];
        }
        return Promise.resolve(); // 确保返回一个 resolved 的 Promise
      } catch (error) {
        console.error('查询出差记录失败:', error);
        this.$message.error('查询出差记录失败');
        return Promise.reject(error);
      }
    },

    openTripDialog(doe, scope) {
      this.tripDoe = doe;
      this.tripScope = scope;

      if (doe === 1) {
        this.tripForm = {
          number: '',
          create_time: '',
          update_time: '',
          creator: this.useName,
          process_status: '',
          sys_update_user: this.useName,
          sys_audit_user: '',
          sys_audit_time: '',
          sys_deleted: 0,
          name: '',
          department: '',
          section: '',
          gender: '',
          fare: '',
          passportNumber: '',
          business: '',
          busineseBegan: '',
          enterRussiaOne: '',
          leftRussiaOne: '',
          enterRussiaTwo: '',
          leftRussiaTwo: '',
          enterRussiaThree: '',
          leftRussiaThree: '',
          enterRussiaFour: '',
          leftRussiaFour: '',
          flightNumber: '',
          phoneNumber: '',
          roomNumber: '',
          cancel: '',
          birthDate: ''

        };
      } else if (doe === 2) {
        this.tripForm = _.cloneDeep(scope.row);
      }
      this.enterRussiaOnePickerOptions = {};
      this.leftRussiaOnePickerOptions = {};
      this.enterRussiaTwoPickerOptions = {};
      this.leftRussiaTwoPickerOptions = {};
      this.enterRussiaThreePickerOptions = {};
      this.leftRussiaThreePickerOptions = {};
      this.enterRussiaFourPickerOptions = {};
      this.leftRussiaFourPickerOptions = {};
      this.tripDialogVisible = true;
    },
    watch: {
      // 监听business字段变化，更新日期选择器限制
      'tripForm.business'(newVal) {
        if (newVal && this.tripForm.enterRussiaOne) {
          this.updateDatePickerOptions();
        }
      }
    },
    async editorTripOk() {
      if (!this.validateDates()) {
        this.$message.error(this.dateErrors.join('; '));
        return;
      }

      try {
        let result;

        if (this.tripDoe === 1) {
          result = await this.$request.post('/addChineseTrip', this.tripForm);
        } else if (this.tripDoe === 2) {
          const updateData = {
            ...this.tripForm,
            update_time: new Date().toISOString(),
            sys_update_user: this.useName
          };
          result = await this.$request.post('/editChineseTrip', updateData);
        }

        if (result.code === 401) {
          this.$router.push('UserLogin');
          this.$message.error("您未登录，请登录");
        } else {
          this.$message.success(
              this.tripDoe === 1 ? "成功添加出差记录" : "成功更新出差记录"
          );
          this.tripDialogVisible = false;
          await this.queryAllChineseTrip();
        }
      } catch (error) {
        this.$message.error(
            this.tripDoe === 1 ? "添加出差记录失败" : "更新出差记录失败"
        );
        console.error(error);
      }
    },


    // Excel上传相关方法
    openExcelUploadDialog() {
      this.excelUploadDialogVisible = true;
      this.selectedFile = null;
      this.uploadResult = null;
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.value = '';
        }
      });
    },

    closeExcelUploadDialog() {
      this.excelUploadDialogVisible = false;
      this.selectedFile = null;
      this.uploadResult = null;
    },

    handleExcelFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      const isValidType = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(file.type);
      if (!isValidType) {
        this.$message.error('请上传有效的Excel文件(.xlsx或.xls)');
        this.$refs.upload.value = '';
        return;
      }

      if (file.size > 10 * 1024 * 1024) {
        this.$message.error('文件大小不能超过10MB');
        this.$refs.upload.value = '';
        return;
      }

      this.selectedFile = file;
    },

    async submitExcelUpload() {
      if (!this.selectedFile) {
        this.$message.warning('请选择要上传的Excel文件');
        return;
      }

      this.uploadLoading = true;

      try {
        const data = await this.readExcelFile(this.selectedFile);
        const chineseTripData = this.transformExcelData(data);

        let successCount = 0;
        let failCount = 0;
        const failDetails = [];

        for (const [index, trip] of chineseTripData.entries()) {
          try {
            // 准备完整的更新数据
            const updateData = {
              ...trip,
              update_time: new Date().toISOString(),
              sys_update_user: this.useName
            };

            // 检查是否已存在相同工号的记录
            const existingRecord = this.chineseTripData.find(item => item.number === trip.number);

            let result;
            if (existingRecord) {
              // 更新现有记录
              updateData.id = existingRecord.id; // 保留原记录ID
              result = await this.$request.post('/editChineseTrip', updateData);
            } else {
              // 添加新记录
              updateData.creator = this.useName;
              updateData.create_time = new Date().toISOString();
              result = await this.$request.post('/addChineseTrip', updateData);
            }

            if (result.code === 200 || result.msg === 'success') {
              successCount++;
            } else {
              failCount++;
              failDetails.push({
                row: index + 2,
                reason: result.msg || '操作失败'
              });
            }
          } catch (error) {
            failCount++;
            failDetails.push({
              row: index + 2,
              reason: '接口调用异常: ' + (error.message || '未知错误')
            });
          }
        }

        this.uploadResult = {
          success: successCount,
          fail: failCount,
          failDetails: failDetails
        };

        if (failCount === 0) {
          this.$message.success(`成功处理 ${successCount} 条数据`);
          this.closeExcelUploadDialog();
          await this.queryAllChineseTrip();
        } else {
          this.$message.warning(`处理完成，成功 ${successCount} 条，失败 ${failCount} 条`);
        }
      } catch (error) {
        console.error('上传Excel失败:', error);
        this.$message.error('处理Excel文件失败: ' + (error.message || '未知错误'));
      } finally {
        this.uploadLoading = false;
      }
    },


    readExcelFile(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (e) => {
          try {
            const data = new Uint8Array(e.target.result);
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

            const filteredData = jsonData.filter(row =>
                row.length > 0 && row.some(cell => cell !== null && cell !== '')
            );

            resolve(filteredData);
          } catch (error) {
            reject(error);
          }
        };

        reader.onerror = (error) => reject(error);
        reader.readAsArrayBuffer(file);
      });
    },

    transformExcelData(excelData) {
      if (!excelData || excelData.length < 2) {
        throw new Error('Excel文件格式不正确或没有数据');
      }

      const headers = excelData[0];
      const dataRows = excelData.slice(1);

      // 定义完整的字段映射，与导出字段保持一致
      const headerMapping = {
        '工号': 'number',
        '姓名': 'name',
        '部门': 'department',
        '科室': 'section',
        '性别': 'gender',
        '费用': 'fare',
        '护照号码': 'passportNumber',
        '签证': 'business',
        '签证开始时间': 'busineseBegan',
        '第一次入境俄罗斯': 'enterRussiaOne',
        '第一次离开俄罗斯': 'leftRussiaOne',
        '第二次入境俄罗斯': 'enterRussiaTwo',
        '第二次离开俄罗斯': 'leftRussiaTwo',
        '第三次入境俄罗斯': 'enterRussiaThree',
        '第三次离开俄罗斯': 'leftRussiaThree',
        '第四次入境俄罗斯': 'enterRussiaFour',
        '第四次离开俄罗斯': 'leftRussiaFour',
        '航班号': 'flightNumber',
        '手机号': 'phoneNumber',
        '房间号': 'roomNumber',
        '取消状态': 'cancel',
        '出生日期': 'birthDate',
        '创建时间': 'create_time',
        '更新时间': 'update_time',
        '创建人': 'creator',
        '处理状态': 'process_status',
        '系统更新用户': 'sys_update_user',
        '系统审核用户': 'sys_audit_user',
        '系统审核时间': 'sys_audit_time',
        '系统删除标记': 'sys_deleted'
      };

      // 检查必需的字段
      const requiredHeaders = ['工号', '姓名', '部门'];
      const missingHeaders = requiredHeaders.filter(header => !headers.includes(header));

      if (missingHeaders.length > 0) {
        throw new Error(`Excel文件中缺少必要的列: ${missingHeaders.join(', ')}`);
      }

      return dataRows.map(row => {
        const trip = {};

        headers.forEach((header, index) => {
          if (headerMapping[header]) {
            let value = row[index];

            // 特殊处理日期字段
            if ([
              'busineseBegan', 'enterRussiaOne', 'leftRussiaOne',
              'enterRussiaTwo', 'leftRussiaTwo', 'enterRussiaThree',
              'leftRussiaThree', 'enterRussiaFour', 'leftRussiaFour',
              'create_time', 'update_time', 'sys_audit_time', 'birthDate'
            ].includes(headerMapping[header])) {
              if (value && typeof value === 'string') {
                const date = this.parseExcelDate(value);
                if (date) {
                  value = date;
                }
              } else if (value && typeof value === 'number') {
                // 处理Excel数字日期
                const date = new Date(Math.round((value - 25569) * 86400 * 1000));
                value = date.toISOString();
              }
            }

            // 特殊处理数字字段
            if (['sys_deleted', 'cancel'].includes(headerMapping[header])) {
              if (value !== undefined && value !== '') {
                value = Number(value);
              }
            }

            trip[headerMapping[header]] = value !== undefined && value !== null ? String(value).trim() :
                (headerMapping[header].endsWith('time') ? new Date().toISOString() : '');
          }
        });

        // 设置默认值
        trip.sys_deleted = trip.sys_deleted || 0;
        trip.cancel = trip.cancel || '0';
        trip.creator = trip.creator || this.useName;
        trip.sys_update_user = this.useName;

        return trip;
      });
    },

    parseExcelDate(dateValue) {
      if (!dateValue) return null;

      if (typeof dateValue === 'number') {
        const date = new Date(Math.round((dateValue - 25569) * 86400 * 1000));
        return this.formatDate(date);
      }

      if (typeof dateValue === 'string') {
        if (/^\d{4}[-/]\d{2}[-/]\d{2}$/.test(dateValue)) {
          return dateValue;
        }

        const date = new Date(dateValue);
        if (!isNaN(date.getTime())) {
          return this.formatDate(date);
        }
      }

      return null;
    },


    downloadExcelTemplate() {
      const wb = XLSX.utils.book_new();
      const wsData = [
        [
          '工号', '姓名', '部门', '科室', '性别', '费用', '护照号码', '签证', '签证开始时间',
          '第一次入境俄罗斯', '第一次离开俄罗斯', '第二次入境俄罗斯', '第二次离开俄罗斯',
          '第三次入境俄罗斯', '第三次离开俄罗斯', '第四次入境俄罗斯', '第四次离开俄罗斯'
        ],
        [
          'GW1001', '张三', '技术部', '软件科', '男', '5000', 'E12345678', '项目开发', '2023-01-15',
          '2023-01-10', '2023-01-20', '2023-02-10', '2023-02-20',
          '2023-03-10', '2023-03-20', '2023-04-10', '2023-04-20'
        ]
      ];

      const ws = XLSX.utils.aoa_to_sheet(wsData);
      XLSX.utils.book_append_sheet(wb, ws, '出差记录模板');
      XLSX.writeFile(wb, '出差记录模板.xlsx');
    },

    // 其他方法
    logOut() {
      localStorage.removeItem('u_token');
      localStorage.removeItem('userName');
      this.$router.push('UserLogin');
    },


    buttonMainSelect(doe) {
      this.buttonDoe = doe;
      this.activeButton = doe;
      if (doe === 1 || doe === 2 || doe === 3 || doe === 4|| doe === 5|| doe === 6|| doe === 7 ) {
        this.queryAllChineseTrip().then(() => {
          if (doe === 3) {
            this.generateSimplifiedData();
          } else if (doe === 4) {
            this.calculateMonthlyStay();
          }
          if (doe === 5) {
            this.generateSimplifiedData();
          }

        });
      }
    },

    generateUUIDv4() {
      const bytes = new Uint8Array(16);
      crypto.getRandomValues(bytes);
      bytes[6] = (bytes[6] & 0x0f) | 0x40;
      bytes[8] = (bytes[8] & 0x3f) | 0x80;
      return Array.from(bytes, byte => {
        return byte.toString(16).padStart(2, '0');
      }).join('');
    },
  },
  computed: {
    filteredChineseTripData() {
      if (this.useName === '刘浩') {
        // 刘浩看到所有记录
        return this.chineseTripData;
      } else {
        // 其他用户只看到自己创建的记录
        return this.chineseTripData.filter(item => item.process_status === this.useName);
      }},


    filteredBusData() {
      if (!this.simplifiedTripData) return [];

      const today = new Date();
      today.setHours(0, 0, 0, 0); // 重置为当天的午夜时间

      return this.simplifiedTripData
          .map(item => {
            if (!item.date) return null;

            const date = new Date(item.date);
            date.setHours(0, 0, 0, 0); // 同样将目标日期重置为午夜时间

            const timeDiff = date.getTime() - today.getTime();  // 计算当前时间与目标时间的差值
            const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // 转换为天数差值

            let daysDiffText = '';
            if (daysDiff > 1) {
              daysDiffText = `还有 ${daysDiff} 天`;
            } else if (daysDiff === 1) {
              daysDiffText = '明天';
            } else if (daysDiff < 0) {
              daysDiffText = `已过期 ${Math.abs(daysDiff)} 天`;
            } else {
              daysDiffText = '就是今天';
            }

            return {
              ...item,
              daysDiff,
              daysDiffText,
              timestamp: date.getTime()  // 用于排序
            };
          })
          .filter(item => {
            // 过滤掉超过14天的记录（不管是未来还是过去）
            return item && Math.abs(item.daysDiff) <= 45; // 如果是14天范围内的记录，才保留
          })
          .sort((a, b) => {
            // 按日期排序（最新的在前）
            return b.timestamp - a.timestamp;
          });
    }

  },

  mounted() {
    this.inquiry();
    this.queryAllChineseTrip().then(() => {
      // 默认显示当前年的月度统计（如果当前在第四页）
      if (this.buttonDoe === 4) {
        this.calculateMonthlyStay();
      }
    });
  },
}

</script>

<style scoped>
.el-header {
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 42px;
}

.el-main {
  color: #333;
  text-align: center;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  overflow: auto;
}

.headMain {
  color: #ffffff;
  font-size: 18px;
}

.center-text {
  margin-left: auto;
  margin-right: auto;
}

.el-table {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.el-table th {
  background-color: #f5f7fa !important;
}

.el-aside {
  background-color: #ffffff;
  color: #333;
  text-align: center;
  border: 1px solid #ebeef5;
  padding: 10px;
}

.aside-button {
  width: 100%;
  margin: 0 0 10px 0;
  text-align: left;
  padding: 12px 16px;
  border-radius: 0;
}

.upload-demo {
  width: 100%;
}

.el-upload-dragger {
  width: 100% !important;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  background-color: #fafafa;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 40px;
  color: #409EFF;
  margin-bottom: 10px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  margin-top: 7px;
}
.entry-record {
  margin: 8px 0;
  padding: 5px 0;
  border-bottom: 1px dashed #eee;
}

.entry-record:last-child {
  border-bottom: none;
}

.entry-index {
  font-weight: bold;
  margin-right: 10px;
  color: #409EFF;
}

.entry-date {
  margin-right: 15px;
  display: inline-block;
  min-width: 80px;
}

.entry-record {
  margin: 5px 0;
  padding: 5px;
}

.entry-type {
  font-weight: bold;
  margin-right: 10px;
  color: #409EFF;
  display: inline-block;
  min-width: 40px;
}

.entry-date {
  display: inline-block;
}
/* 月度状态表样式 */
.monthly-status-container {
  width: 100%;
  overflow: auto;
}

.table-wrapper {
  overflow-x: auto;
  max-height: 70vh;
  border: 1px solid #ebeef5;
}

.monthly-status-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.monthly-status-table th {
  background: #f5f7fa;
  font-weight: bold;
  position: sticky;
  top: 0;
  z-index: 5;
}

.monthly-status-table thead th {
  position: sticky;
  top: 0;
  z-index: 10;
}
/* 更新月度状态表样式 */
.monthly-status-table th:nth-child(4),
.monthly-status-table td:nth-child(4) {
  position: sticky;
  left: 300px;
  background: #f5f7fa;
  z-index: 5;
}

/* 调整其他列的 sticky 位置 */
.monthly-status-table th:nth-child(1),
.monthly-status-table td:nth-child(1) {
  left: 0;
}

.monthly-status-table th:nth-child(2),
.monthly-status-table td:nth-child(2) {
  left: 100px;
}

.monthly-status-table th:nth-child(3),
.monthly-status-table td:nth-child(3) {
  left: 200px;
}
.monthly-status-table tbody tr:hover {
  background: #f5f7fa;
}

.monthly-status-table tbody td:hover {
  filter: brightness(0.9);
}

.date-header {
  min-width: 40px;
}

.date-display {
  font-size: 12px;
  font-weight: bold;
}

.weekday-display {
  font-size: 10px;
  color: #666;
}

.status-cell {
  transition: all 0.2s;
}

.status-cell:hover {
  transform: scale(1.1);
  z-index: 2;
  position: relative;
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .monthly-status-table {
    font-size: 10px;
  }

  .date-header {
    min-width: 30px;
  }
}
/* 更新月度状态表样式 */
.monthly-status-table th:nth-child(3),
.monthly-status-table td:nth-child(3) {
  position: sticky;
  left: 200px;
  background: #f5f7fa;
  z-index: 5;
}

/* 调整其他列的 sticky 位置 */
.monthly-status-table th:nth-child(1),
.monthly-status-table td:nth-child(1) {
  left: 0;
}

.monthly-status-table th:nth-child(2),
.monthly-status-table td:nth-child(2) {
  left: 100px;
}
</style>
